<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/2
 * Time: 17:06
 */

namespace backend\services;

use backend\models\PlayerRankingTbl;
use yii;

class RefreshService
{
    public function refreshData()
    {
        $sql = "truncate Player_Ranking_tbl";
        yii::$app->db->createCommand($sql)->execute();
        $transation = yii::$app->db->beginTransaction();
        try{
            //财富榜（金币数量前20）
            $player = new PlayerRankingTbl();
            $data = $player->getNewPlayerGoldCoinData();
            foreach ($data as $key=>$value){
                $data[$key]['Rank'] = $key + 1;
                $data[$key]['RankType'] = 1;
                $data[$key]['PointCount'] = $value['GoldCoin'];
                $data[$key]['UpdateTime'] = date('Y-m-d H:i:s', time());
                unset($data[$key]['GoldCoin']);
            }
            $params = ['PlayerID','FaceUrl','PlayerName','Rank','RankType','PointCount','UpdateTime'];
            yii::$app->db->createCommand()->batchInsert('Player_Ranking_tbl', $params, $data)->execute();

            //对局榜（对局总和前20）
            $data2 = $player->getConfrontationData();
            foreach ($data2 as $key=>$value){
                $data2[$key]['Rank'] = $key + 1;
                $data2[$key]['RankType'] = 2;
                $data2[$key]['PointCount'] = $value['GameNumber'];
                $data2[$key]['UpdateTime'] = date('Y-m-d H:i:s', time());
                unset($data2[$key]['GameNumber']);
            }
            yii::$app->db->createCommand()->batchInsert('Player_Ranking_tbl', $params, $data2)->execute();

            //冠军榜（冠军次数前20）
            $data3 = $player->getChampionData();
            foreach ($data3 as $key=>$value){
                $data3[$key]['Rank'] = $key + 1;
                $data3[$key]['RankType'] = 3;
                $data3[$key]['PointCount'] = $value['ChampNum'];
                $data3[$key]['UpdateTime'] = date('Y-m-d H:i:s', time());
                unset($data3[$key]['ChampNum']);
            }
            yii::$app->db->createCommand()->batchInsert('Player_Ranking_tbl', $params, $data3)->execute();
            $transation->commit();
            return ['statusCode'=>200, 'message'=>'更新数据成功'];
        }catch (\Exception $e){
            $transation->rollBack();
            return ['statusCode'=>300, 'message'=>'更新失败'];
        }

    }
}